package com.stray.crawl.expr.act;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.stray.crawl.BeanContext;
import com.stray.crawl.ResultContext;
import com.stray.crawl.TaskContext;
import com.stray.crawl.expr.EventData;
import com.stray.crawl.expr.Express;
import com.stray.crawl.supt.FileStorage;
import com.stray.crawl.utils.IOUtils;

public class FilePersistAction extends Express {

	private final Log log = LogFactory.getLog(this.getClass());

	private FileStorage storage = BeanContext.get(FileStorage.class);

	@Override
	protected Object doParse(EventData event) {
		TaskContext taskContext = event.getTaskContext();
		ResultContext resultContext = event.getResultContext();

		try {
			File file = storage.getPersistDirectoryFile(taskContext.getPlanName());
			String filename = UUID.randomUUID().toString();
			File targetPath = new File(file, filename + ".txt");
			StringBuffer buf = new StringBuffer();

			List<Object[]> results = resultContext.getResults();
			String[] fields = taskContext.getFields();

			boolean firstObject = true;;
			
			for (Object[] objs : results) {
				if (!firstObject) {
					buf.append(",\r\n");
				}
				buf.append("\t{");
				boolean first = true;
				for (int i = 0; i < fields.length; i++) {
					if (!first) {
						buf.append(",");
					}
					
					buf.append("\r\n\t\t");
					buf.append("\"" + fields[i] + "\" : ");
					buf.append("\"" + String.valueOf(objs[i]).replace('"', '\'') + "\"");

					first = false;
				}

				buf.append("\r\n\t}");
				firstObject = false;
			}
			
			IOUtils.writeFile(targetPath.getCanonicalPath(), "{ \"fields\" : [\r\n\t" + buf.toString() + "\r\n] }");
		} catch (IOException ex) {
			log.warn("Fail to persist resultContext. ", ex);
		}

		return null;
	}

}